﻿using Net8.Project.Common.Core;
using SqlSugar;

namespace Net8.Project.Common.Caches
{
    /// <summary>
    /// 实现SqlSugar的ICacheService接口
    /// </summary>
    public class SqlSugarCache : ICacheService
    {
        private readonly Lazy<ICaching> _caching = new(() => App.GetService<ICaching>(false));
        private ICaching Caching => _caching.Value;

        public void Add<TValue>(string key, TValue value)
        {
            Caching.Set(key, value);
        }

        public void Add<TValue>(string key, TValue value, int cacheDurationInSeconds)
        {
            Caching.Set(key, value, TimeSpan.FromSeconds(cacheDurationInSeconds));
        }

        public bool ContainsKey<TValue>(string key)
        {
            return Caching.Exists(key);
        }

        public TValue Get<TValue>(string key)
        {
            return Caching.Get<TValue>(key);
        }

        public IEnumerable<string> GetAllKey<TValue>()
        {
            return Caching.GetAllCacheKeys();
        }

        public TValue GetOrCreate<TValue>(string cacheKey, Func<TValue> create, int cacheDurationInSeconds = int.MaxValue)
        {
            if (!ContainsKey<TValue>(cacheKey))
            {
                var value = create();
                Caching.Set(cacheKey, value, TimeSpan.FromSeconds(cacheDurationInSeconds));
                return value;
            }

            return Caching.Get<TValue>(cacheKey);
        }

        public void Remove<TValue>(string key)
        {
            Caching.Remove(key);
        }

        public bool RemoveAll()
        {
            Caching.RemoveAll();
            return true;
        }
    }
}
